package org.mcjug.locationmailer.util;

import org.mcjug.locationmailer.service.LocationService;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class AlarmManagerUtil {

	public static void updateAlarm(Context context) {
		cancelAlarm(context);

		long interval = getInterval(context);
		if (interval != Constants.LOCATION_UPDATE_INTERVAL_NONE) {

			// Setup alarm service to wake up and start service periodically
			AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
			alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, 
					0, interval, getPendingIntent(context));
		}
	}

	public static void cancelAlarm(Context context) {
		AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		alarmManager.cancel(getPendingIntent(context));
 	}
	
	public static void resetAlarm(Context context) {
		cancelAlarm(context);
		updateAlarm(context);
 	}
	
	public static PendingIntent getPendingIntent(Context context) {
		Intent intent = new Intent(context, LocationService.class);
		return PendingIntent.getService(context, -1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
	}	
	
	public static long getInterval(Context context) {	
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		int interval = Constants.LOCATION_UPDATE_INTERVAL_NONE;
		String intervalStr = prefs.getString(
				Constants.PREFS_LOCATION_UPDATE_INTERVAL_KEY,
				String.valueOf(interval));
		try {
			interval = Integer.parseInt(intervalStr);
		} catch (NumberFormatException e) {
		}
		
	    return interval;
	}
}
